var express = require('express');
var router = express.Router();

const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
const bcrypt = require('bcryptjs');
const response = require('../utils/response');
const verifyToken = require('../middleware/auth');
const jwt = require('jsonwebtoken');

/**
 * @description 创建管理员
 * @route POST /users
 */
router.post('/', verifyToken, async (req, res) => {
  try {
    const { username, password, nickname, email, phone, remark } = req.body;
    
    // 密码加密
    const hashedPassword = await bcrypt.hash(password, 10);
    
    // 检查用户名是否已存在
    const existingAdmin = await prisma.admin.findUnique({
      where: { username }
    });

    if (existingAdmin) {
      return res.status(400).json(response(false, '用户名已存在', null, 400));
    }

    const admin = await prisma.admin.create({
      data: {
        username,
        password: hashedPassword,
        nickname,
        email,
        phone,
        remark
      }
    });

    res.json(response(true, '创建成功', admin));
  } catch (error) {
    res.status(500).json(response(false, error.message, null, 500));
  }
});

/**
 * @description 获取管理员列表
 * @route GET /users
 * @param {number} page - 页码
 * @param {number} pageSize - 每页数量
 */
router.get('/', verifyToken, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 10;
    const skip = (page - 1) * pageSize;

    const [total, admins] = await Promise.all([
      prisma.admin.count(),
      prisma.admin.findMany({
        skip,
        take: pageSize,
        select: {
          id: true,
          username: true,
          nickname: true,
          avatar: true,
          email: true,
          phone: true,
          status: true,
          lastLoginTime: true,
          lastLoginIp: true,
          remark: true,
          createdAt: true,
          updatedAt: true
        }
      })
    ]);

    res.json(response(true, '获取成功', {
      list: admins,
      pagination: {
        total,
        page,
        pageSize,
        totalPages: Math.ceil(total / pageSize)
      }
    }));
  } catch (error) {
    res.status(500).json(response(false, error.message, null, 500));
  }
});

/**
 * @description 获取管理员详情
 * @route GET /users/:id
 */
router.get('/:id', verifyToken, async (req, res) => {
  try {
    const { id } = req.params;
    
    const admin = await prisma.admin.findUnique({
      where: { id: parseInt(id) },
      select: {
        id: true,
        username: true,
        nickname: true,
        avatar: true,
        email: true,
        phone: true,
        status: true,
        lastLoginTime: true,
        lastLoginIp: true,
        remark: true,
        createdAt: true,
        updatedAt: true
      }
    });

    if (!admin) {
      return res.status(404).json(response(false, '管理员不存在', null, 404));
    }

    res.json(response(true, '获取成功', admin));
  } catch (error) {
    res.status(500).json(response(false, error.message, null, 500));
  }
});

/**
 * @description 更新管理员信息
 * @route PUT /users/:id
 */
router.put('/:id', verifyToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { nickname, email, phone, status, remark } = req.body;
    
    const admin = await prisma.admin.update({
      where: { id: parseInt(id) },
      data: {
        nickname,
        email,
        phone,
        status,
        remark
      }
    });

    res.json(response(true, '更新成功', admin));
  } catch (error) {
    res.status(500).json(response(false, error.message, null, 500));
  }
});

/**
 * @description 删除管理员
 * @route DELETE /users/:id
 */
router.delete('/:id', verifyToken, async (req, res) => {
  try {
    const { id } = req.params;
    
    await prisma.admin.delete({
      where: { id: parseInt(id) }
    });

    res.json(response(true, '删除成功'));
  } catch (error) {
    res.status(500).json(response(false, error.message, null, 500));
  }
});

/**
 * @description 管理员登录
 * @route POST /users/login
 */
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;

    // 验证用户名和密码是否为空
    if (!username || !password) {
      return res.status(400).json(response(false, '用户名和密码不能为空', null, 400));
    }

    // 查找用户
    const admin = await prisma.admin.findUnique({
      where: { username }
    });

    // 用户不存在
    if (!admin) {
      return res.status(400).json(response(false, '用户名或密码错误', null, 400));
    }

    // 验证密码
    const isValidPassword = await bcrypt.compare(password, admin.password);
    if (!isValidPassword) {
      return res.status(400).json(response(false, '用户名或密码错误', null, 400));
    }

    // 生成 token
    const token = jwt.sign(
      { 
        id: admin.id,
        username: admin.username 
      },
      process.env.JWT_SECRET || 'your-secret-key',  // 建议使用环境变量
      { expiresIn: '24h' }  // token 有效期为24小时
    );

    // 删除密码字段
    delete admin.password;

    res.json(response(true, '登录成功', {
      token,
      userInfo: admin
    }));
  } catch (error) {
    res.status(500).json(response(false, error.message, null, 500));
  }
});



module.exports = router;
